package com.xzz.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.xzz.domain.CourseOrder;
import com.xzz.domain.PayFlow;
import com.xzz.domain.PayOrder;
import com.xzz.dto.Order2PayOrderParamDto;
import com.xzz.mapper.PayOrderMapper;
import com.xzz.service.IPayFlowService;
import com.xzz.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xzz.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xzz
 * @since 2022-09-18
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {

    @Autowired
    private IPayFlowService payFlowService;

    //保存支付单，订单是给客人的，支付的给支付宝的
    @Override
    public void savePayOrder(Order2PayOrderParamDto orderDto) {
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(orderDto,payOrder);

        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.STATE_WAITE_PAY);
        insert(payOrder);
    }

    //通过订单号查询，是否支付单已经存在
    @Override
    public PayOrder selectByOrderNo(String orderNo){
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        PayOrder payOrder = selectOne(wrapper);
        return payOrder;
    }

    //更新支付单数据，以及添加支付流水
    @Override
    public void updatePayOrderAndInsertPayFlow(PayOrder payOrder, PayFlow payFlow) {
        PayOrder tmp = selectById(payOrder.getId());
        //处理消息的幂等问题
        AssertUtil.isTrue(tmp.getPayStatus() == PayOrder.STATE_WAITE_PAY,"支付单状态不合法");
        updateById(payOrder);
        payFlowService.insert(payFlow);
    }

    @Override
    public void closeOrder(String orderNo) {
        PayOrder payOrder = selectByOrderNo(orderNo);
        if (payOrder==null){
            return;
        }
        if(payOrder.getPayStatus()!=CourseOrder.STATE_WAITE_PAY){
            return;
        }
        log.info("支付超时取消，取消支付单");
        payOrder.setPayStatus(PayOrder.STATE_CANCEL);
        updateById(payOrder);
        try {
            //支付宝关单方法
            Factory.Payment.Common().close(orderNo);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("调用退款接口，来退款");
        }
    }
}
